package com.arron.jvm.ref;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

/**
 * @Classname PhantomRefDemo
 * @Date 2020/8/24 1:02
 * @Created by 刘
 */
public class PhantomRefDemo {

    /**
     * 虚引用，不管死否发生GC都是null,通常用于通知机制，对象垃圾回收监控，在对象回收前做一些行为处理
     *  主要作用用于跟踪对象被垃圾回收的状态
     */
    public static void main(String[] args) throws InterruptedException {

        Object o1 = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Object> reference = new PhantomReference<>(o1, referenceQueue);

        System.out.println("==========GC之前============");
        System.out.println(o1);
        System.out.println(reference.get());
        System.out.println(referenceQueue.poll());


        o1=null;
        System.gc();
        Thread.sleep(500);

        System.out.println("==========GC之后============");
        System.out.println(o1);
        System.out.println(reference.get());
        System.out.println(referenceQueue.poll());
    }

}
